package com.wwwarehouse.carddesk.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.wwwarehouse.carddesk.R;
import com.wwwarehouse.carddesk.activity.CardDeskActivity;
import com.wwwarehouse.carddesk.eventbus_event.CardDeskFunctionFilterEvent;
import com.wwwarehouse.carddesk.eventbus_event.CardDeskTaskFilterEvent;
import com.wwwarehouse.carddesk.eventbus_event.CardDeskTaskFunctionEvent;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CardDeskTaskResponseBean;
import com.wwwarehouse.common.eventbus_event.CardDeskRefreshEvent;
import com.wwwarehouse.common.eventbus_event.DrawerMultipleCompleteEvent;
import com.wwwarehouse.common.eventbus_event.DrawerMultipleResetEvent;
import com.wwwarehouse.common.tools.PopUpUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import de.greenrobot.event.EventBus;

@Route(path = "/carddesk/DeskTaskFragment")
public class DeskTaskFragment extends BaseFragment {
    private View mRootView;

    private TaskTabFragment mTaskTabFragment;
    private FunctionTabFragment mFunctionTabFragment;
    private Fragment mCurrentFragment;

    private String TAG_TASK = "task";
    private String TAG_TASK_TASK = "task_task";
    private String TAG_TASK_FUNCTION = "task_function";

    //记录当前在哪个页面
    private String mCurrentTag = "";

    private int mSelectedTaskPosition = 2;
    private int mSelectedFunctionPosition = 2;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_desk_task, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initData();
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return null;
    }

    private void initView() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    private void initData() {
        //默认显示任务TAB
        switchFragment(TAG_TASK_TASK);
    }

    @Override
    public void filterClick() {
        //初始化抽屉数据
        if (peekFragment() == null && TAG_TASK.equals(((CardDeskActivity) mActivity).getTabCurr())) {
            if (mTaskTabFragment != null && mTaskTabFragment.isVisible()) {
                mTaskTabFragment.initDrawerLayout();
            } else if (mFunctionTabFragment != null && mFunctionTabFragment.isVisible()) {
                mFunctionTabFragment.initDrawerLayout();
            }

            ((BaseCardDeskActivity) mActivity).showDrawerLayout();
        }
    }

    //搜索
    @Override
    public void searchNoRealTimeClick(String text) {
        if (peekFragment() == null && TAG_TASK.equals(((CardDeskActivity) mActivity).getTabCurr())) {
            //搜索框为空的时候，关闭键盘，不搜索
            if (!TextUtils.isEmpty(text)) {
                if (mTaskTabFragment != null && mTaskTabFragment.isVisible()) {
                    mTaskTabFragment.setSearchText(text);
                    mTaskTabFragment.getTaskInfo(true);
                } else if (mFunctionTabFragment != null && mFunctionTabFragment.isVisible()) {
                    mFunctionTabFragment.setSearchText(text);
                    mFunctionTabFragment.getFunctionInfo(true);
                }
            }
        }
    }

    //取消
    @Override
    public void cancelClick() {
        if (peekFragment() == null && TAG_TASK.equals(((CardDeskActivity) mActivity).getTabCurr())) {
            if (mTaskTabFragment != null && mTaskTabFragment.isVisible()) {
                mTaskTabFragment.setSearchText("");
                mTaskTabFragment.getTaskInfo(true);
            } else if (mFunctionTabFragment != null && mFunctionTabFragment.isVisible()) {
                mFunctionTabFragment.setSearchText("");
                mFunctionTabFragment.getFunctionInfo(true);
            }
        }
    }

    //排序
    @Override
    public void sortClick(View anchor) {
        if (peekFragment() == null && TAG_TASK.equals(((CardDeskActivity) mActivity).getTabCurr())) {
            if (mTaskTabFragment != null && mTaskTabFragment.isVisible()) {
                PopUpUtils.showBubbleInviteSort(mActivity, anchor, mSelectedTaskPosition, new PopUpUtils.OnChoiceListener() {
                    @Override
                    public void onChoice(int position) {
                        mSelectedTaskPosition = position;

                        switch (position) {
                            case 2:
                                mTaskTabFragment.setOrderSort("ASC");
                                mTaskTabFragment.setOrderType("emergency_degree");   //默认排序，紧急程度排序
                                break;
                            case 3:
                                mTaskTabFragment.setOrderSort("DESC");
                                mTaskTabFragment.setOrderType("allot_time");         //任务接收时间排序
                                break;
                            default:
                                break;
                        }

                        mTaskTabFragment.getTaskInfo();
                    }
                }, null, getString(R.string.sort_by_emergency_degree), getString(R.string.sort_by_allot_time));
            } else if (mFunctionTabFragment != null && mFunctionTabFragment.isVisible()) {
                PopUpUtils.showBubbleInviteSort(mActivity, anchor, mSelectedFunctionPosition, new PopUpUtils.OnChoiceListener() {
                    @Override
                    public void onChoice(int position) {
                        mSelectedFunctionPosition = position;

                        switch (position) {
                            case 2:
                                mFunctionTabFragment.setOrderSort("DESC");
                                mFunctionTabFragment.setOrderType("TASK_UNIT_RATE");   //默认排序，使用频率排序
                                break;
                            case 3:
                                mFunctionTabFragment.setOrderSort("DESC");
                                mFunctionTabFragment.setOrderType("TASK_UNIT_TIME");  //获取功能时间排序
                                break;
                            default:
                                break;
                        }

                        mFunctionTabFragment.getFunctionInfo();
                    }
                }, null, getString(R.string.sort_by_use_rate), getString(R.string.sort_by_obtain_time));
            }
        }
    }

    public void onEventMainThread(CardDeskTaskFunctionEvent event) {
        String msg = event.getMsg();

        switchFragment(msg);

        // 切换TAB刷新数据
        if (TAG_TASK_TASK.equals(msg)) {
            mTaskTabFragment.getTaskInfo();
        } else if (TAG_TASK_FUNCTION.equals(msg)) {
            mFunctionTabFragment.getFunctionInfo();
        }
    }

    public void onEventMainThread(CardDeskRefreshEvent event) {
        String message = event.getMsg();

        if (TAG_TASK_TASK.equals(mCurrentTag)) {
            mTaskTabFragment.getTaskInfo();
        } else if (TAG_TASK_FUNCTION.equals(mCurrentTag)) {
            mFunctionTabFragment.getFunctionInfo();
        }
    }

    public void onEventMainThread(CardDeskTaskFilterEvent event) {
        mSelectedTaskPosition = event.getPosition();
    }

    public void onEventMainThread(CardDeskFunctionFilterEvent event) {
        mSelectedFunctionPosition = event.getPosition();
    }

    public void onEventMainThread(DrawerMultipleCompleteEvent event) {
        if (peekFragment() == null && (TAG_TASK.equals(((CardDeskActivity) mActivity).getTabCurr()))) {
            if (mTaskTabFragment != null && mTaskTabFragment.isVisible()) {
                Set<String> taskTagSet = new HashSet<>();
                List<CardDeskTaskResponseBean.TaskTagBean> taskTagList = mTaskTabFragment.getTaskTagList();

                Set<Integer> selectedPositionSet = event.getSelectedPositionSet();
                for (int position : selectedPositionSet) {
                    taskTagSet.add(taskTagList.get(position).getTagValue());
                }

                mTaskTabFragment.setTaskTagSet(taskTagSet);
                mTaskTabFragment.getTaskInfo();
            } else if (mFunctionTabFragment != null && mFunctionTabFragment.isVisible()) {
                Set<String> taskTagSet = new HashSet<>();
                List<CardDeskFunctionResponseBean.TaskTagBean> taskTagList = mFunctionTabFragment.getTaskTagList();

                Set<Integer> selectedPositionSet = event.getSelectedPositionSet();
                for (int position : selectedPositionSet) {
                    taskTagSet.add(taskTagList.get(position).getTagValue());
                }

                mFunctionTabFragment.setTaskTagSet(taskTagSet);
                mFunctionTabFragment.getFunctionInfo();
            }
        }
    }

    public void onEventMainThread(DrawerMultipleResetEvent event) {
        if (peekFragment() == null && (TAG_TASK.equals(((CardDeskActivity) mActivity).getTabCurr()))) {
            if (mTaskTabFragment != null && mTaskTabFragment.isVisible()) {
                Set<String> taskTagSet = new HashSet<>();
                mTaskTabFragment.setTaskTagSet(taskTagSet);
            } else if (mFunctionTabFragment != null && mFunctionTabFragment.isVisible()) {
                Set<String> taskTagSet = new HashSet<>();
                mFunctionTabFragment.setTaskTagSet(taskTagSet);
            }
        }
    }

    @Override
    public void setTitle() {

    }

    @Override
    public void requestDatas() {

    }

    private void switchFragment(String tag) {
        mCurrentTag = tag;

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        Fragment toFragment = fragmentManager.findFragmentByTag(tag);

        if (toFragment == null) {
            if (TAG_TASK_TASK.equals(tag)) {
                mTaskTabFragment = new TaskTabFragment();
                toFragment = mTaskTabFragment;
            } else if (TAG_TASK_FUNCTION.equals(tag)) {
                mFunctionTabFragment = new FunctionTabFragment();
                toFragment = mFunctionTabFragment;
            }
        }

        if (mCurrentFragment != null) {
            if (mCurrentFragment != toFragment) {
                if (!toFragment.isAdded()) {
                    fragmentTransaction.add(R.id.rl_desk_task, toFragment, tag).hide(mCurrentFragment);
                } else {
                    fragmentTransaction.show(toFragment).hide(mCurrentFragment);
                }
            }
        } else {
            if (!toFragment.isAdded()) {
                fragmentTransaction.add(R.id.rl_desk_task, toFragment, tag);
            } else {
                fragmentTransaction.show(toFragment);
            }
        }

        mCurrentFragment = toFragment;
        fragmentTransaction.commitAllowingStateLoss();
    }
}
